package com.heima.wemedia.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.BeanHelper;
import com.heima.utils.common.JsonUtils;
import com.heima.utils.common.ThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public PageResponseResult findList(WmNewsPageReqDto dto) {
        System.out.println("进入findList");
        dto.checkParam();
        WmUser wmUser = (WmUser)ThreadLocalUtils.get();
        if (wmUser == null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        PageHelper.startPage(dto.getPage(),dto.getSize());
        List<WmNews> list = wmNewsMapper.findById(wmUser.getId(),dto);
        PageInfo<WmNews> pageInfo = new PageInfo<>(list);
        dto.getKeyword();
        dto.getStatus();
        // 封装结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getList());
        responseResult.setErrorMessage("查询成功");
        responseResult.setCode(200);

        return responseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        WmUser wmUser = (WmUser) ThreadLocalUtils.get();
        if (wmUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = BeanHelper.copyProperties(dto,WmNews.class);
        // 作者
        wmNews.setUserId(wmUser.getId());

        // 提取文章内容中的所有图片
        List<String> contentImages = getImagesFromContent(wmNews);


        // 判断是否为自动封面
        if (dto.getType() == -1){
            // 自动封面
            int size = contentImages.size();
            if (size==0){
                wmNews.setType((short) 0);
                wmNews.setImages(null);
            }
            if (size>=1 && size<=2){
                // 单图
                wmNews.setType((short) 1);
                wmNews.setImages(contentImages.get(0)); //截取第一张图片作为封面
            }
            if (size>=3){
                // 三图
                wmNews.setType((short) 3);
                // subList() 截取集合的元素
//                contentImages.subList(0,3); // 包前不包后 [0,3)
                String collect = contentImages.subList(0, 3).stream().collect(Collectors.joining(","));
            }

        }else {
            // 非自动封面
//            List<String> images = dto.getImages();
//            StringBuilder coverImage = new StringBuilder();
//            for (String img:images){
//                coverImage.append(images);
//            }
            // 使用JDK1.8 Stream编程
            if (!CollectionUtils.isEmpty(dto.getImages())){
                // joining()：使用指定分隔符号拼接字符串
                String coverImage = dto.getImages().stream().collect(Collectors.joining(","));
                wmNews.setImages(coverImage);
            }


        }


        // 判断是新增还是修改
        if (dto.getId() == null){
            // 如果是新增，直接添加
            wmNews.setCreatedTime(new Date());
            wmNewsMaterialMapper.save(wmNews);
        }else {
            // 是修改，修改文章
//            wmNewsMaterialMapper.update(wmNews);
            // 并且删除当前文章和素材的所有关系

//            wmNewsMaterialMapper.delete(wmNews.getId());
        }
        // 内容素材与文章绑定（type=0）
        if (!CollectionUtils.isEmpty(contentImages)){
            // 把url转换为id
            List<Integer> materialIds = getMaterialIdsFromUrl(contentImages);
            System.out.println(materialIds);
            wmNewsMaterialMapper.saveNewsMaterials(materialIds,wmNews.getId(),0);
        }
        // 封面素材与文章绑定（type=1）
        if (StringUtils.isNotEmpty(wmNews.getImages())){
            List<String> images = Arrays.asList(wmNews.getImages().split(","));
            // 把url转换为id
            List<Integer> materialIds = getMaterialIdsFromUrl(images);
            wmNewsMaterialMapper.saveNewsMaterials(materialIds,wmNews.getId(),1);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /*
        根据url查询id
     */
    private List<Integer> getMaterialIdsFromUrl(List<String> urls) {
        List<WmMaterial> wmMaterials = wmMaterialMapper.queryByList(urls);
        if (!CollectionUtils.isEmpty(wmMaterials)){
            return wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        }
        return null;
    }

    private List<String> getImagesFromContent(WmNews wmNews) {
        List<String> images = new ArrayList<>();
        if (StringUtils.isNotEmpty(wmNews.getContent())){
            List<Map> list = JsonUtils.toList(wmNews.getContent(), Map.class);
            for (Map map:list){
                if (map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }
        return images;


    }
}
